import React, { Component } from 'react';
import {
  View,
  StyleSheet,
  Text,
  ScrollView,
  Image,
  TextInput,
  TouchableOpacity,
  FlatList,
  RefreshControl
} from 'react-native';

import NavBar from '../../../components/PublicHeader';
import { Images } from '../../../public/images/images';
import { Constant } from '../../../public/js/constant';
import fetchWebApi from '../../../public/WebApi/fetchBase';
import { POST_USER_AGREE, GET_USER_NEWFRIENDS, POST_USER_SEARCH, DELETE_USER_EMPTY } from '../../../public/WebApi/mailListApi';
import getStorageValue from '../../../utils/getStorageValue';

const datalist = [];

export default class newfriends extends Component {
  constructor(props) {
    super(props);
    this.state = {
      datalist: [],
      flags: true,
      userList: [],
      flags2: false,
      isRefreshing: false
    };
  }

  componentDidMount = () => {
    this.getUserNewfriend()
  };

  // 好友请求列表
  async getUserNewfriend() {
    const res = await fetchWebApi(GET_USER_NEWFRIENDS, { token: await getStorageValue(Constant.TOKEN) }, 'GET');
    console.log(res);
    if (res.status == 200) {
      this.setState({
        datalist: res.data
      })
    }
    if (this.state.datalist == '') {
      this.setState({
        flags: false
      })
    }
  }

  // 同意好友
  async agree(item) {
    const res = await fetchWebApi(POST_USER_AGREE, { token: await getStorageValue(Constant.TOKEN), friendId: item.friendId }, 'POST');
    if (res.status == 200) {
      this.setState({
        flag: (item.flag = 1)
      })
    }
    this.props.navigation.state.params.refresh()
  }

  // 搜索用户
  async PostSearch(values) {
    const res = await fetchWebApi(POST_USER_SEARCH, { token: await getStorageValue(Constant.TOKEN), phone: values }, 'POST')
    console.log('##############');
    console.log(res);
    if (res.status == 200) {
      // 电话号码超过11位数
      if (values.length == 11) {
        if (res.data != null) {
          this.setState({
            userList: res.data,
            flags2: true
          })
        } else {

        }
      }
    }
  }

  // 清空好友请求列表
  async DeleteNewfriend() {
    const res = await fetchWebApi(DELETE_USER_EMPTY, { token: await getStorageValue(Constant.TOKEN) }, 'DELETE')
    if (res.status == 200) {
      this.setState({
        flags: false
      })
    }
  }

  // 判断诚信等级
  reputations(item) {
    return (
      parseInt(item) == 1 ?
        <>
          <Text style={{ color: '#FDE400' }}>★</Text>
          <Text style={{ color: '#C4C4C4' }}>★</Text>
          <Text style={{ color: '#C4C4C4' }}>★</Text>
          <Text style={{ color: '#C4C4C4' }}>★</Text>
          <Text style={{ color: '#C4C4C4' }}>★</Text>
        </> : parseInt(item) == 2 ?
          <>
            <Text style={{ color: '#FDE400' }}>★</Text>
            <Text style={{ color: '#FDE400' }}>★</Text>
            <Text style={{ color: '#C4C4C4' }}>★</Text>
            <Text style={{ color: '#C4C4C4' }}>★</Text>
            <Text style={{ color: '#C4C4C4' }}>★</Text>
          </> : parseInt(item) == 3 ?
            <>
              <Text style={{ color: '#FDE400' }}>★</Text>
              <Text style={{ color: '#FDE400' }}>★</Text>
              <Text style={{ color: '#FDE400' }}>★</Text>
              <Text style={{ color: '#C4C4C4' }}>★</Text>
              <Text style={{ color: '#C4C4C4' }}>★</Text>
            </> : parseInt(item) == 4 ?
              <>
                <Text style={{ color: '#FDE400' }}>★</Text>
                <Text style={{ color: '#FDE400' }}>★</Text>
                <Text style={{ color: '#FDE400' }}>★</Text>
                <Text style={{ color: '#FDE400' }}>★</Text>
                <Text style={{ color: '#C4C4C4' }}>★</Text>
              </> : parseInt(item) == 5 ?
                <>
                  <Text style={{ color: '#FDE400' }}>★</Text>
                  <Text style={{ color: '#FDE400' }}>★</Text>
                  <Text style={{ color: '#FDE400' }}>★</Text>
                  <Text style={{ color: '#FDE400' }}>★</Text>
                  <Text style={{ color: '#FDE400' }}>★</Text>
                </> : parseInt(item) == 0 ?
                  <>
                    <Text style={{ color: '#C4C4C4' }}>★</Text>
                    <Text style={{ color: '#C4C4C4' }}>★</Text>
                    <Text style={{ color: '#C4C4C4' }}>★</Text>
                    <Text style={{ color: '#C4C4C4' }}>★</Text>
                    <Text style={{ color: '#C4C4C4' }}>★</Text>
                  </> : null
    )
  }


  handleRefresh = () => {
    this.setState({
      isRefreshing: true,//tag,下拉刷新中，加载完全，就设置成flase
      datalist: [],
    });
    this.getUserNewfriend()
    this.setState({
      isRefreshing: false
    })
  }

  render() {
    const Item = ({ item }) => {
      return (
        <View style={styles.body_list}>
          <TouchableOpacity onPress={() => {
            this.props.navigation.navigate('introduces', {
              params: item.flag,
              id: item.friendId,
              remarksName: item.remarksName != null ? item.remarksName : item.nickName,
              refresh: () => {
                this.props.navigation.state.params.refresh()
              },
            });
          }} style={styles.list_view}>
            <TouchableOpacity onPress={() => {
              this.props.navigation.navigate('introduces', {
                params: item.flag,
                id: item.friendId,
                remarksName: item.remarksName != null ? item.remarksName : item.nickName,
                refresh: () => {
                  this.props.navigation.state.params.refresh()
                },
              });
            }}
            >
              <Image source={{ uri: item.avatar }} style={{ width: 47, height: 47, borderRadius: 6 }} />
            </TouchableOpacity>
            <View>
              <Text style={styles.list_text}>{item.remarksName != null ? item.remarksName : item.nickName}</Text>
              <Text style={styles.list_text2}>对方留言：{item.addFriendMessage}</Text>
            </View>
          </TouchableOpacity>
          <View style={styles.evaluate}>
            {/* 判断是否同意好友 */}
            {
              item.flag == 0 ?
                <>
                  <TouchableOpacity onPress={() => {
                    this.agree(item)
                  }} style={styles.btn}>
                    <Text style={styles.btn_text}>同意</Text>
                  </TouchableOpacity>
                </> :
                item.flag == 1 ? <>
                  <TouchableOpacity onPress={() => {
                  }} style={styles.btn2}
                    disabled>
                    <Text style={styles.btn_text2}>已同意</Text>
                  </TouchableOpacity>
                </> :
                  item.flag == 2 ?
                    <>
                      <TouchableOpacity onPress={() => {
                      }} style={styles.btn2}
                        disabled>
                        <Text style={styles.btn_text2}>已过期</Text>
                      </TouchableOpacity>
                    </> : null
            }
          </View>
        </View>
      )
    }
    const Item2 = ({ item }) => {
      return (
        <TouchableOpacity onPress={() => {
          this.props.navigation.navigate('introduces', {
            id: item.id,
            remarksName: item.remark != null ? item.remark : item.nickName,
            refresh: () => {
              this.props.navigation.state.params.refresh()
            },
          });
        }} style={styles.body_list_search}>
          <View style={styles.list_view}>
            <View>
              <Image style={{ width: 47, height: 47, borderRadius: 6 }} source={{ uri: item.avatar }} />
            </View>
            <View style={styles.list_view2}>
              <View style={styles.enterprise}>
                <Text style={styles.list_text_search}>{item.nickName}</Text>
                <Image style={{ marginLeft: 5, width: 18, height: 18 }} source={item.userType == 1 ? require('../../../assets/images/maillist/enterprise.png') : null} />
              </View>
              <Text style={styles.list_text_search2}>座右铭：{item.motto == '' ? '用户很懒，暂未添加座右铭' : item.motto == null ? '用户很懒，暂未添加座右铭' : item.motto}</Text>
            </View>
          </View>
          <View style={styles.evaluatess}>
            {this.reputations(item.creditLevel)}
          </View>
        </TouchableOpacity>
      )
    }
    // 好友请求列表
    let datalists =
      <>
        <FlatList
          // ItemSeparatorComponent={this.space}
          showsVerticalScrollIndicator={false}
          data={this.state.datalist}
          renderItem={Item}
          keyExtractor={item => String(item.friendId)}
          refreshControl={
            <RefreshControl
              refreshing={this.state.isRefreshing}
              onRefresh={this.handleRefresh.bind(this)}//因为涉及到this.state
              colors={['#ff0000', '#00ff00', '#0000ff', '#3ad564']}
              progressBackgroundColor="#ffffff"
            />
          }
          initialNumToRender={6}
        />
      </>

    let empty =
      <>
        <View style={styles.empty}>
          <Text style={styles.empty_text}>暂时没有新的朋友~</Text>
        </View>
      </>

    // 搜索用户列表
    let userlist =
      <>
        <FlatList
          // ItemSeparatorComponent={this.space}
          showsVerticalScrollIndicator={false}
          data={this.state.userList}
          renderItem={Item2}
          keyExtractor={item => String(item.friendId)}
          refreshControl={
            <RefreshControl
              refreshing={this.state.isRefreshing}
              onRefresh={this.handleRefresh.bind(this)}//因为涉及到this.state
              colors={['#ff0000', '#00ff00', '#0000ff', '#3ad564']}
              progressBackgroundColor="#ffffff"
            />
          }
          initialNumToRender={6}
        />
      </>
    return (
      <View style={{ flex: 1, backgroundColor: '#fff' }}>
        <NavBar
          navigation={this.props.navigation}
          title={'新的朋友'}
          right={'清空'}
          pressRight={() => {
            this.DeleteNewfriend()
          }}
        />
        <View style={styles.bds}>
          <View style={styles.bodys_input}>
            {/* 搜索框 */}
            <TextInput
              style={styles.inputs}
              inlineImageLeft="sou"
              placeholder="电话号码搜索用户"
              placeholderTextColor="#00000069"
              inlineImagePadding={40}
              onChange={(value) => {
                const values = value.nativeEvent.text
                if (values.length == 11) {
                  this.PostSearch(values)
                } else {
                  this.setState({
                    userList: [],
                    flags2: false
                  })
                }
              }}
              keyboardType={'numeric'}
            />
          </View>
          <View>
            {/* 循环好友请求列表 */}
            {this.state.flags2 ? userlist : this.state.flags ? datalists : empty}
          </View>
        </View >
      </View>
    );
  }
}
const styles = StyleSheet.create({
  container: {
    display: 'flex',
    flexDirection: 'row',
    alignItems: 'center',
    height: 32,
    backgroundColor: 'transparent',
  },
  bds: {
    padding: 15
  },
  bodys_input: {
    paddingBottom: 10,
    backgroundColor: '#fff',
  },
  inputs: {
    paddingLeft: 15,
    borderRadius: 10,
    color: 'black',
    backgroundColor: '#C4C4C440',
  },
  body_list: {
    display: 'flex',
    flexDirection: 'row',
    paddingLeft: 5,
    borderBottomWidth: 1,
    borderBottomColor: '#f2f2f2',
    padding: 5,
    backgroundColor: '#fff',
    justifyContent: 'space-between'
  },
  body_list_search: {
    display: 'flex',
    flexDirection: 'row',
    paddingLeft: 5,
    padding: 15,
    justifyContent: 'space-between',
    borderBottomWidth: 1,
    borderBottomColor: '#ccc'
  },
  list_view: {
    display: 'flex',
    flexDirection: 'row',
    justifyContent: 'flex-start'
  },
  list_view2: {
    display: 'flex',
    flexDirection: 'column',
    justifyContent: 'space-between',
    paddingLeft: 10
  },
  list_text: {
    color: '#333',
    paddingLeft: 10,
    fontSize: 18,
  },
  list_text_search: {
    color: '#333',
    fontSize: 18,
  },
  list_text_search2: {
    color: '#999',
    fontSize: 11,
  },
  list_text2: {
    color: 'rgb(115,115,115)',
    paddingLeft: 11,
    fontSize: 11,
    padding: 6,
  },
  evaluate: {
    width: 47,
    height: 22,
    borderRadius: 6,
    marginVertical: 10,
  },
  evaluatess: {
    display: 'flex',
    flexDirection: 'row',
  },
  empty: {
    flexDirection: 'column',
    justifyContent: 'center',
    marginTop: 30
  },
  empty_text: {
    color: '#ccc',
    fontSize: 22,
    textAlignVertical: 'center',
    textAlign: 'center',
    includeFontPadding: false
  },
  btn: {
    backgroundColor: '#1890FF',
    flexDirection: 'column',
    justifyContent: 'center',
    borderRadius: 3,
    padding: 2,
  },
  btn_text: {
    color: '#fff',
    textAlign: 'center',
    textAlignVertical: 'center',
    includeFontPadding: false
  },
  btn2: {
    width: 47,
    height: 22,
    padding: 2,
    justifyContent: 'center',
    alignItems: "center",
    borderWidth: 1,
    borderColor: '#c7c7c7',
    borderRadius: 3,
  },
  btn_text2: {
    fontSize: 12,
    color: '#c7c7c7',
    textAlign: 'center',
    textAlignVertical: 'center',
    includeFontPadding: false
  },
  enterprise: {
    display: 'flex',
    flexDirection: 'row',
    alignItems: 'center',
  }
});
